import { Card,Button, Checkbox, Form, Input ,message} from 'antd'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'
import logo from '../../assets/logo.png'   // 图片login
import { loginAction } from '../../store/action/login'
import './index.scss'// 样式

const Login = () => {
  // 表达数据
  const dispatch = useDispatch()
  const hs = useHistory()
  const onFinish = async (formData) => {
    console.log('Success:', formData);
    try {
      await dispatch (loginAction(formData))
      message.success('登录成功');
     
      hs.replace('/home')
    } catch (error) {
        message.error(error.response.data.message);
      
      
    }
   
  };
  // 用户协议正则   自定义校验
  const vakudArgee = (rule,value) =>{
    // console.log(value，rule);当前表单项的校验值
    if(value){
      return  Promise.resolve()      
    }else{
      return Promise.reject(new Error('请勾选用户协议'))    
    }
      
  }  
  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
    <Form
      name="basic"
      initialValues= {{
        mobile: '13911111111',
        code: '246810',
        Agree: true,
      }}
      //  只有当表达校验通过才可以运行onFinish 
      onFinish={onFinish}
      autoComplete="off"
    >
      {/*
      表单验的核心
      form.item指定name的属性  name属性和后台登录接口需要的参数名保持一致(必须)
     通过rules 指定表单单项校验规则 
      validateTrigger={['onBlur']} 正则输入完成之后在触发
     */}
      <Form.Item
      validateTrigger={['onBlur']}
        name="mobile"
        rules={[
          {
            required:true,
            message:'请输入手机号'
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号'
          },
        ]}
      >
      <Input size='large' placeholder='请输入手机号'/>
      </Form.Item>

      <Form.Item
        name="code"
        validateTrigger={['onBlur']}
        rules={[
          {
            required: true,
            message: '请输入验证码',
          },
          {
            len: 6,
            message: '请输入正确长度的验证码',
          },
        ]}
      >
        <Input size='large'placeholder='请输入验证码' />
      </Form.Item>

      <Form.Item
        name="agree"
        valuePropName="checked"
        rules={[{validator:vakudArgee}]}
      >
        <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
      </Form.Item>

      <Form.Item
      >
        <Button type="primary" block htmlType="submit" size='large'>
          登录
        </Button>
      </Form.Item>
    </Form>
      </Card>
    </div>
  )
}

export default Login